package com.crcode.crm.controller.file;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;

import com.crcode.crm.utils.ConfigUtil;
import com.crcode.crm.utils.MyFileUtil;
import com.crcode.crm.utils.POIReadExcelToHtml;


/**
 * excel、word转html
 * @author cl
 * @date 2019年4月19日
 */
@Controller
public class ToHtmlController {
	/**
	 * 文件转成html
	 * @param request
	 * @param response
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "/fileToHtml")
	public String fileToHtml(HttpServletRequest request,HttpServletResponse response,String filePath) throws Exception {
		ConfigUtil config = ConfigUtil.getInstance();// 读取配置文件
		String accessoryPath = config.getProperty("contextRoot");// 地址
		String path = accessoryPath+filePath.substring(0,filePath.lastIndexOf("/"));
		String htmlName=filePath.substring(filePath.lastIndexOf("/")+1,filePath.lastIndexOf("."));
		File file = new File(path, htmlName+".html");
		if(file.exists()){
			return "success";
		}
		String fileType = filePath.substring(filePath.lastIndexOf(".")+1);
		InputStream input = new FileInputStream(accessoryPath+filePath); 
		Document htmlDocument=null;
		if(fileType.contains("doc")){
			HWPFDocument wordDocument = new HWPFDocument(input); 
			WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter( DocumentBuilderFactory.newInstance().newDocumentBuilder() .newDocument()); 
			wordToHtmlConverter.setPicturesManager(new PicturesManager() {public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) { return suggestedName; }}); 
			wordToHtmlConverter.processDocument(wordDocument);
			List pics = wordDocument.getPicturesTable().getAllPictures();
			if (pics != null) {
				for (int i = 0; i < pics.size(); i++) { 
					Picture pic = (Picture) pics.get(i); 
					try { 
						pic.writeImageContent(new FileOutputStream(path + pic.suggestFullFileName())); 
					} catch (FileNotFoundException e) { 
						e.printStackTrace(); 
					} 
				} 
			}
			htmlDocument = wordToHtmlConverter.getDocument(); 
		}else if(fileType.contains("xls")){
			HSSFWorkbook excelBook=new HSSFWorkbook(input); 
			ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() ); 
			excelToHtmlConverter.processWorkbook(excelBook);
			htmlDocument =excelToHtmlConverter.getDocument();
		}
		ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
		DOMSource domSource = new DOMSource(htmlDocument); 
		StreamResult streamResult = new StreamResult(outStream); 
		TransformerFactory tf = TransformerFactory.newInstance(); 
		Transformer serializer = tf.newTransformer(); 
		serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); 
		serializer.setOutputProperty(OutputKeys.INDENT, "yes"); 
		serializer.setOutputProperty(OutputKeys.METHOD, "html"); 
		serializer.transform(domSource, streamResult); 
		outStream.close(); 
		String content = new String(outStream.toByteArray()); 
		FileUtils.writeStringToFile(new File(path, htmlName+".html"), content, "utf-8");
		return "success";
	}
	
	
	
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "/toHtml")
	public String toHtml(HttpServletRequest request,HttpServletResponse response,String filePath) throws Exception {
		ConfigUtil config = ConfigUtil.getInstance();// 读取配置文件
		String accessoryPath = config.getProperty("contextRoot");// 地址
		String path = accessoryPath+filePath.substring(0,filePath.lastIndexOf("/"));
		String htmlName=filePath.substring(filePath.lastIndexOf("/")+1,filePath.lastIndexOf("."));
		File file = new File(path, htmlName+".html");
		if(file.exists()){
			return "success";
		}
		String fileType = filePath.substring(filePath.lastIndexOf(".")+1).toLowerCase();
		InputStream input = new FileInputStream(accessoryPath+filePath); 
		String content="";
		try{
			if (fileType.contains("doc")){
				try{
					HWPFDocument wordDocument = new HWPFDocument(input); 
					WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
							DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
							wordToHtmlConverter.setPicturesManager(new PicturesManager() {public String savePicture(byte[] content, PictureType pictureType,
							     String suggestedName, float widthInches, float heightInches) {    
							    return "/crm/DATA/"+filePath.substring(0,filePath.lastIndexOf("/")+1)+htmlName+"/"+suggestedName; //图片在html页面加载路径
							   }
							  });
					wordToHtmlConverter.processDocument(wordDocument);
					//处理图片
					List pics = wordDocument.getPicturesTable().getAllPictures();
					if (pics != null) {
						MyFileUtil.makeDir(path +"/"+htmlName+"/");
						for (int i = 0; i < pics.size(); i++) { 
							Picture pic = (Picture) pics.get(i); 
							try { 
								pic.writeImageContent(new FileOutputStream(path +"/"+htmlName+"/"+ pic.suggestFullFileName())); 
							} catch (FileNotFoundException e) { 
								e.printStackTrace(); 
							} 
						} 
					}
					//创建html页面并将文档中内容写入页面
					Document htmlDocument = wordToHtmlConverter.getDocument(); 
					ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
					DOMSource domSource = new DOMSource(htmlDocument); 
					StreamResult streamResult = new StreamResult(outStream); 
					TransformerFactory tf = TransformerFactory.newInstance(); 
					Transformer serializer = tf.newTransformer(); 
					serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); 
					serializer.setOutputProperty(OutputKeys.INDENT, "yes"); 
					serializer.setOutputProperty(OutputKeys.METHOD, "html"); 
					serializer.transform(domSource, streamResult); 
					content = new String(outStream.toByteArray());
					outStream.close(); 
				} catch (Exception ex) {
					input = new FileInputStream(accessoryPath+filePath);
					// 1) 加载word文档生成 XWPFDocument对象  
		            XWPFDocument document = new XWPFDocument(input);  
		            // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)  
		            File imageFolderFile = new File(path);  
		            XHTMLOptions options = XHTMLOptions.create().URIResolver(new BasicURIResolver("/crm/DATA/"+filePath.substring(0,filePath.lastIndexOf("/")+1)));  
		            options.setExtractor(new FileImageExtractor(imageFolderFile)); 
		            options.setIgnoreStylesIfUnused(false);
		            options.setFragment(true); 
		            // 3) 将 XWPFDocument转换成XHTML  
//		            OutputStream out = new FileOutputStream(file);  
//		            XHTMLConverter.getInstance().convert(document, out, options);  
		            //也可以使用字符数组流获取解析的内容
		            ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
		            XHTMLConverter.getInstance().convert(document, baos, options);  
		            content = baos.toString();
		            baos.close();
		        } 
			}else if (fileType.contains("xls")){
				try{
					HSSFWorkbook excelBook=new HSSFWorkbook(input); 
					ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() ); 
					excelToHtmlConverter.processWorkbook(excelBook);
					Document htmlDocument =excelToHtmlConverter.getDocument();
					ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
					DOMSource domSource = new DOMSource(htmlDocument); 
					StreamResult streamResult = new StreamResult(outStream); 
					TransformerFactory tf = TransformerFactory.newInstance(); 
					Transformer serializer = tf.newTransformer(); 
					serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); 
					serializer.setOutputProperty(OutputKeys.INDENT, "yes"); 
					serializer.setOutputProperty(OutputKeys.METHOD, "html"); 
					serializer.transform(domSource, streamResult); 
					content = new String(outStream.toByteArray());
					outStream.close(); 
				}catch (Exception ex) {
					input = new FileInputStream(accessoryPath+filePath);
					XSSFWorkbook excelBook=new XSSFWorkbook(input);
					content = POIReadExcelToHtml.getExcelInfo(excelBook,true);
				}
			}
			FileUtils.writeStringToFile(new File(path, htmlName+".html"), content, "utf-8");
			return "success";
		}catch (Exception e) {
//			throw new Exception(e);
			return "false";
		}
	}
}
